package gl.pk.db;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import gl.pk.db.model.Item;
import gl.pk.db.model.Magic;
import gl.pk.db.model.Monster;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 从文本导入到mysql数据库
 */
@Slf4j
public class DbMirImport {
    private static String[] DbFiles = {"怪物.txt", "技能.txt", "物品.txt"};
    private static Map<String, String> Db2FileMap = new HashMap();
    private static Map<String, Class> Db2BeanMap = new HashMap();

    static {
        Db2FileMap.put("monster", DbFiles[0]);
        Db2FileMap.put("magic", DbFiles[1]);
        Db2FileMap.put("item", DbFiles[2]);
        Db2BeanMap.put("monster", Monster.class);
        Db2BeanMap.put("magic", Magic.class);
        Db2BeanMap.put("item", Item.class);
    }

    private static String Path = PathKit.getWebRootPath() + "/../../resource/db";

    public static void main(String[] args) throws IOException, SQLException, IllegalAccessException, InstantiationException {
        DataSource dataSource = DBUtil.init().getDataSource();
        Connection conn = dataSource.getConnection();
        DatabaseMetaData md = conn.getMetaData();

        MetaBuilder metaBuilder = new MetaBuilder(dataSource);
        Iterator var2 = metaBuilder.build().iterator();
        while (var2.hasNext()) {
            TableMeta tableMeta = (TableMeta) var2.next();
            System.out.println("===== " + tableMeta.name + " ======");
            if (Db2FileMap.containsKey(tableMeta.name)) {

                ResultSet rs = md.getColumns(conn.getCatalog(), (String) null, tableMeta.name, (String) null);
                List<ColumnMeta> keyList = new ArrayList<>();
                while (rs.next()) {
                    ColumnMeta columnMeta = new ColumnMeta();
                    columnMeta.name = rs.getString("COLUMN_NAME");
                    columnMeta.type = rs.getString("TYPE_NAME");
                    keyList.add(columnMeta);
                    System.out.print(" | " + columnMeta.name + "(" + columnMeta.type + ") ");
                }

                List<String> valueList = insetByLine(Path, Db2FileMap.get(tableMeta.name));
                for (String s : valueList) {
                    String[] columnValues = s.split(";");
                    Model model = (Model) Db2BeanMap.get(tableMeta.name).newInstance();
                    for (int i = 0; i < columnValues.length; i++) {
                        ColumnMeta columnMeta = keyList.get(i);
                        String columnValue = columnValues[i];
                        if (columnMeta.type.equalsIgnoreCase("int") && "".equals(columnValues[i])) {
                            columnValue = "0";
                        }
                        model.set(columnMeta.name, columnValue);
                    }
                    try {
                        model.save();
                        System.out.println(model);
                    } catch (ActiveRecordException e) {
                        if (e.getMessage().indexOf("Duplicate entry") > 0) {
                            log.warn("[warn] this data have exist, insert be ignore:" + model);
                        } else {
                            e.printStackTrace();

                        }
                    }
                }


            }
            System.out.println("");
            System.out.println("---------------------");
        }

    }

    private static List<String> insetByLine(String path, String dbFile) throws IOException {
        BufferedReader bis = new BufferedReader(new FileReader(new File(path, dbFile)));
        String line;
        List<String> lineList = new ArrayList();
        while ((line = bis.readLine()) != null) {
            lineList.add(line);
        }
        return lineList;
    }
}
